//
//  TeachSignerMessageController.m
//  Coach_HaiGeEr
//
//  Created by liuchen on 2018/10/16.
//  Copyright © 2018年 海格尔. All rights reserved.
//

#import "TeachSignerMessageController.h"
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
#import <MJRefresh.h>
#import "MJExtension.h"
#import "TeachSignerCell.h"
#import "TeachSignerTwoCell.h"

#import "TeachManagementModel.h"

@interface TeachSignerMessageController ()<UITableViewDelegate,UITableViewDataSource,TeachSignerCellDelegate,TeachSignerTwoCellDelegate>
@property (nonatomic,strong) UIImageView *noDataImgView;
@property (nonatomic,strong) UITableView *signerTableView;
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,assign) NSInteger size;
@property (nonatomic,assign) BOOL styleJudge;
@end

@implementation TeachSignerMessageController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[CoachTabBarController shareLZHTabbarController].tabBar setHidden:YES];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createSubViews];
}

#pragma mark ==========视图==========
- (void)createSubViews{
    [self setNavBack];
    
    self.title = @"学员签到信息";
    self.size = 10;
    
    NSDateComponents *cmps = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
    self.styleJudge = [self.currentDate isEqualToString:[NSString stringWithFormat:@"%zd-%02zd-%02zd", cmps.year, cmps.month, cmps.day]]?YES:NO;
    
    [self.view addSubview:self.noDataImgView];
    [self.view addSubview:self.signerTableView];
    
    [self showLoading];
    [self loadDataWithSize:self.size WithIds:self.ids WithSubjectType:self.subjectType WithCurrentDate:self.currentDate];
}

#pragma mark ==========加载数据==========
- (void)loadDataWithSize:(NSInteger)size WithIds:(NSNumber *)ids WithSubjectType:(NSNumber *)subjectType WithCurrentDate:(NSString *)currentDate{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:[NSNumber numberWithInteger:size] forKey:@"size"];
    [dic setValue:[NSNumber numberWithInteger:1] forKey:@"page"];
    [dic setValue:ids forKey:@"ids"];
    [dic setValue:subjectType forKey:@"subjectType"];
    [dic setValue:currentDate forKey:@"currentDate"];
    [[NetworkEngine sharedClient] GETByToken:TEACHFISTPAGEWITHSIGNDetail data:dic success:^(id responseObject) {
        [self hideHUD];
        if ([[responseObject objectForKey:@"code"] integerValue] == 1) {
            if ([[responseObject objectForKey:@"data"] count]==0) {
                self.signerTableView.hidden = YES;
                self.noDataImgView.hidden = NO;
            }else {
                if (self.signerTableView.hidden == YES) {
                    self.noDataImgView.hidden = YES;
                    self.signerTableView.hidden = NO;
                }
                self.signerTableView.mj_footer.state = MJRefreshStateIdle;
                if (size==10) {
                    self.dataArray = [[NSMutableArray alloc] initWithArray:[TeachManagementModel mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:@"data"]]];
                }else{
                    if ([[responseObject objectForKey:@"data"] count]==self.dataArray.count) {
                        self.signerTableView.mj_footer.state = MJRefreshStateNoMoreData;
                    } else {
                        self.dataArray = [[NSMutableArray alloc] initWithArray:[TeachManagementModel mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:@"data"]]];
                    }
                }
            }
            [self.signerTableView reloadData];
        }else if ([[responseObject objectForKey:@"code"] integerValue] == 2) {
            [self toLoginVC];
        } else {[self showMessage:[responseObject objectForKey:@"msg"]];}
    } failure:^(NSString *error) {
        [self hideHUD];
    }];
}
- (void)loadNewData{
    [self showLoading];
    self.size = 10;
    [self loadDataWithSize:self.size WithIds:self.ids WithSubjectType:self.subjectType WithCurrentDate:self.currentDate];
    [self.signerTableView.mj_header endRefreshing];
}
- (void)loadMoreData{
    [self showLoading];
    self.size = self.size+10;
    [self loadDataWithSize:self.size WithIds:self.ids WithSubjectType:self.subjectType WithCurrentDate:self.currentDate];
    [self.signerTableView.mj_footer endRefreshing];
}

#pragma mark ==========懒加载==========
- (UIImageView *)noDataImgView{
    if (!_noDataImgView) {
        _noDataImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 179*2*SCALEUNIT, 140*2*SCALEUNIT)];
        _noDataImgView.image = [UIImage imageNamed:@"CoachNoDataImg"];
        _noDataImgView.center = CGPointMake(self.view.frame.size.width/2.0,self.view.frame.size.height/2.0-50*SCALEUNIT);
        _noDataImgView.hidden = YES;
    }
    return _noDataImgView;
}
- (UITableView *)signerTableView{
    
    if (_signerTableView == nil) {
        _signerTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStylePlain];
        _signerTableView.tableFooterView = [[UIView alloc]init];
        _signerTableView.backgroundColor = [UIColor clearColor];
        _signerTableView.delegate = self;
        _signerTableView.dataSource = self;
        _signerTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
        [_signerTableView setSeparatorInset:UIEdgeInsetsMake(0, 30*SCALEUNIT, 0, 30*SCALEUNIT)];
        [_signerTableView setSeparatorColor:RGBA(230, 230, 230, 1)];
        [_signerTableView registerClass:self.styleJudge?[TeachSignerCell class]:[TeachSignerTwoCell class] forCellReuseIdentifier:self.styleJudge?@"TeachSignerCell":@"TeachSignerTwoCell"];
        
        _signerTableView.mj_header = [CustomGifHeader headerWithRefreshingBlock:^{
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self loadNewData];
            });
        }];
        _signerTableView.mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    }
    return _signerTableView;
}

#pragma mark ==========UITableView代理方法==========
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return self.styleJudge?(437-41*2)*SCALEUNIT:170*SCALEUNIT;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *finalCell = nil;
    if (self.styleJudge) {
        TeachSignerCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TeachSignerCell" forIndexPath:indexPath];
        cell.model = [self.dataArray objectAtIndex:indexPath.row];
        cell.delegate = self;
        finalCell = cell;
    } else {
        TeachSignerTwoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TeachSignerTwoCell" forIndexPath:indexPath];
        cell.model = [self.dataArray objectAtIndex:indexPath.row];
        cell.delegate = self;
        finalCell = cell;
    }
    return finalCell;
}

#pragma mark ==========TeachManagementCell代理==========
- (void)teachSignerCellDelegatePhoneWithNum:(NSString *)phone{
    [self phoneOpenWithNum:phone];
}
- (void)teachSignerTwoCellDelegatePhoneWithNum:(NSString *)phone{
    [self phoneOpenWithNum:phone];
}
- (void)phoneOpenWithNum:(NSString *)phone{
    if ([self isSIMInstalled]) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phone]]];
    }else {
        [self showMessage:@"没有sim卡"];
    }
}
- (BOOL)isSIMInstalled{
    CTTelephonyNetworkInfo *networkInfo = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier = [networkInfo subscriberCellularProvider];
    if (!carrier.isoCountryCode) {
        return NO;
    }
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
